<?php

/*
 * Copyright (C) 2009 - 2011 Pham Cong Dinh
 *
 * This file is part of Spica.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

/**
 * This class provides simple mechanism to encode and decode a base-58 number.
 *
 * Base58 is base62 with some confusing characters removed. These removed are 0, O, l, I.
 *
 * @category   spica
 * @package    core
 * @subpackage crypto
 * @author     Pham Cong Dinh <pcdinh at phpvietnam dot net>
 * @author     Dark Launch
 * @since      Version 0.3
 * @since      May 14, 2010
 * @copyright  Pham Cong Dinh (http://www.phpvietnam.net)
 * @license    http://www.gnu.org/licenses/lgpl-3.0.txt
 * @version    $Id: Crypto.php 1775 2010-04-26 10:24:21Z pcdinh $
 */
class SpicaBase58
{
    /**
     * Encodes a number.
     *
     * @param string $num
     * @return string
     */
    public static function encode($num)
    {
        $alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
        $count = strlen($alphabet);
        $encoded = '';

        while ($num >= $count)
        {
            $div = $num / $count;
            $mod = ($num - ($count * intval($div)));
            $encoded = $alphabet[$mod] . $encoded;
            $num = (int) $div;
        }

        if ($num)
        {
            $encoded = $alphabet[$num] . $encoded;
        }

        return $encoded;
    }

    /**
     * Decodes a string.
     *
     * @param string $num
     * @return string
     */
    public static function decode($num)
    {
        $alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
        $len = strlen($num);
        $decoded = 0;
        $multi = 1;

        for ($i = $len - 1; $i >= 0; $i--)
        {
            $decoded += $multi * strpos($alphabet, $num[$i]);
            $multi = $multi * strlen($alphabet);
        }

        return $decoded;
    }
}

?>